﻿using System.Collections.Generic;
using System.Linq;

namespace Manoso.Data.FluentMap
{
    public interface IMapDelete<TP> : IMapCommand<TP>
    {
    }

    internal class MapDelete<TP> : MapCommand<TP>, IMapDelete<TP>
    {
        internal MapDelete()
        {
            IsMatch = NOT_MATCH;
        }

        public override void GetCommand(IMapTask task, IList<string> stack)
        {
            var sub = (TP)task.Values[TableAlias];
            if (!IsMatch(sub)) return;

            if (ActionFix != null) ActionFix(sub);

            var delete = GenerateCommand(task.Adaptor, task);

            if (!string.IsNullOrEmpty(delete))
                task.AddCommand(delete, MapCommandType.Delete);
        }

        private string GenerateCommand(IMapAdaptor adaptor, IMapTask task)
        {
            if (IsTable)
            {
                LoadIds(task);
                var ids = Keys.Select(x => x.Column).ToArray();
                return adaptor.GetDelete(Target, ids);
            }

            LoadProperties(task, true);
            var properties = Columns.Select(x => x.Column).ToArray();

            return adaptor.GetExec(Target, properties);
        }
    }
}